<template>
	<view>
		<button class="btn-block ver-code" :class="{'set':disabled}" hover-class="btn-hover" :loading="loading" :disabled="disabled" @click="sending">{{ showText }}</button>
	</view>
</template>

<script>
	export default {
		data(){
			return {
				num: 60,
				showText: '获取验证码',
				defaultText : '获取验证码',
				loading: false,
				disabled: false,
				timer: null
			}
		},
		created() {
			this.showText = this.$t('components.code')
			this.defaultText  = this.$t('components.code')
		},
		destroyed(){
			clearInterval(this.timer)
		},
		methods: {
			sendCode(){
				let time = 60 //倒计时时间
				const { num, showText, defaultText, loading, disabled } = this
				if(num === time){
					this.loading = false
					this.showText = this.num + 'S'
					this.timer = setInterval(() => {
						if(this.num >= 2){
							this.num--
							this.showText = this.num + 'S'
						} else {
							clearInterval(this.timer)
							this.reset()
						}
					}, 1000)
				}
			},
			sending(){
				this.$emit('send')
			},
			sendEnd(type){
				if(type === 'success'){
					this.sendCode()
				} else {
					this.loading = false
					this.disabled = false
				}
			},
			startRequest(){
				this.loading = true
				this.disabled = true
			},
			reset(){
				clearInterval(this.timer)
				this.timer = null
				this.num = 60
				this.showText = this.$t('components.code')
				this.defaultText  = this.$t('components.code')
				this.loading = false
				this.disabled = false
			}
		}
	}
</script>

<style scoped lang="less">
	.ver-code {
		height: 60upx;
		line-height: 60upx;
		font-size: 24upx;
		color: var(--theme-color);
		border-radius: 30upx;
		min-width: 200upx;
		border: none;
		background: none;
		padding: 0;
		text-align: right;
		&:after {
			display: none;
		}
		&[disabled] {
			background: none;
		}
	}
	.set{
		color: #666666!important;
	}
</style>
